<?php


namespace app\common\model;

class Chatroom extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_chatroom';
    // 主键ID
    protected $pk = 'cm_id';

	/**
	 * 创建聊天室
	 * @param $shop_id
	 * @param $user_id
	 * @param $client_id
	 * @param $type 1是用户  2是店铺客服
	 * @return int
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
    function CreateChatRoom($shop_id,$user_id,$client_id,$type)
    {
        $chatroom = $this
			->field("{$this->pk}")
			->where([
				'shop_id' => $shop_id,
				'user_id' => $user_id,
			])
			->find();

		$client = $type == 1 ?'user_client':'shop_client';

		if(!$chatroom){
			$res = $this->save([
				'shop_id' => $shop_id,
				'user_id' => $user_id,
				'add_time' => time(),
				"{$client}" => $client_id,
			]);
			if(!$res){
				return false;
			}
			return $this->{$this->pk};
		}else{
			$res = $this->save([
				'update_time' => time(),
				"{$client}" => $client_id,
			],[
				"{$this->pk}" => $chatroom["{$this->pk}"],
			]);
			if(!$res){
				return false;
			}
			return $chatroom["{$this->pk}"];
		}
    }

	function GetChatRoom($field,$where){
		$res = $this->field($field)
			->where($where)
			->find();
		return $res;
	}

	function GetChatRoomList($type,$id,$limit = 10){
		//判断接收端，1是用户，2是店铺
		if($type === 1){
			//是用户就查商铺信息
			$name = 'user';
			$field = "cr.cm_id,cr.update_time,s.shop_id,s.shop_name,s.imagesurl";
			$join = [
				['ddt_shops s','cr.shop_id=s.shop_id'],
			];
		}else{
			//是商铺就查用户信息
			$name = 'shop';
			$field = "cr.cm_id,cr.update_time,u.user_id,u.nick_name,u.avatar";
			$join = [
				['ddt_user u','cr.user_id=u.user_id'],
			];
		}

		$field .= ',(select msg FROM ddt_chatroom_message as crm where crm.cm_id=cr.cm_id ORDER BY crm.cmm_id DESC LIMIT 0,1) as msg';
		$field .= ",(select count(crm.cmm_id) FROM ddt_chatroom_message as crm where crm.cm_id=cr.cm_id and {$name}_is_unread=1) as msg_num";
		$res = $this->alias('cr')
			->field($field)
			->where([
				"cr.{$name}_id" => $id
			])
			->order("cr.{$name}_is_unread desc,cr.update_time desc")
			->leftJoin($join)
			->paginate($limit);

		return $res;
	}
}